package com.monitor.display_platform.business.thread.safe.atmic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {

    private static AtomicInteger count = new AtomicInteger();

    //同时并发执行的线程数
    private static final int threadTotal = 200;

    //一共发起5000个请求
    private static final int clientTotal = 5000;


    public static void main(String[] args)throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        final Semaphore semaphore = new Semaphore(threadTotal);
        for (int i = 0; i < clientTotal; i++) {
            executor.execute(()->{
                try {

                    semaphore.acquire();
                    add();

                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println(count.get());
    }

    private static void add(){
        count.incrementAndGet();
    }
}
